package com.walk.zworld.ui

import android.Manifest
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.widget.*
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.core.content.PermissionChecker.PERMISSION_GRANTED
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.base.lib.base.utils.ToastUtil
import com.base.lib.base.view.BaseActivity
import com.base.lib.common.utils.DateUtil
import com.base.lib.common.utils.SPUtils
import com.base.lib.common.utils.SdkVersionUtil
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.tencentmap.mapsdk.maps.TencentMapInitializer
import com.walk.zworld.BuildConfig
import com.walk.zworld.R
import com.walk.zworld.api.bean.ConfigBean
import com.walk.zworld.api.http.CommonAppConfig
import com.walk.zworld.api.utils.WordUtil
import com.walk.zworld.receiver.NetworkChangeReceiver
import com.walk.zworld.ui.activity.LocationDetailActivity
import com.walk.zworld.ui.fragment.*
import com.walk.zworld.ui.location.LocationDetailFragment
import com.walk.zworld.ui.location.MyDetailFragment
import com.walk.zworld.utils.DialogUitl
import com.walk.zworld.utils.PermissionUtils
import com.walk.zworld.utils.observer.DefaultObserver
import com.walk.zworld.webView.WebViewActivity
import kotlin.system.exitProcess


/**
 *
 * 2020-12-23.
 */
class MainActivity : BaseActivity() {

    companion object {
        const val REQ_CODE_INIT_API_KEY = 666
    }

    override fun onBindLayout(): Int = R.layout.activity_main

    /**
     * 网络状态变化的广播
     */
    private var mNetworkChangeReceiver: NetworkChangeReceiver? = null

    //定义是否退出程序的标记
    private var isExit = 0L
    private lateinit var viewPager: ViewPager
    private lateinit var fragments: ArrayList<Fragment> //fragment集合
    private lateinit var titleList: MutableList<String>
    private lateinit var titleResList: MutableList<Int>
    private var pos = 1


    private var zxingCodeUrl: ImageView? = null
    /**
     * 权限申请
     */
    private val permissionArray = arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
       /* Manifest.permission.WRITE_SECURE_SETTINGS,*/
    )
    private var mPermissionList = arrayListOf<String>()
    private lateinit var mPermissionDialog: AlertDialog

    /**
     * newInstance并不能保证fragment是同一个，可能会重新new一个，所以这里设置一下
     */
    private val locationDetailFragment = LocationDetailFragment.newsInstance()
    private val videoLiveFragment = VideoLiveFragment.newsInstance()
//    private val myFragment = MyFragment.newsInstance()
    private val myFragment = MyDetailFragment.newsInstance()

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        overridePendingTransition(
            android.R.anim.fade_in,
            android.R.anim.fade_out
        )
//        setTopTitle("使用手册")
////、        setLeft(R.mipmap.ic_fly) { startActivity(Intent(this, SquarePageActivity::class.java)) }
//        setRight("使用手册") { startActivity(Intent(this, LocationDetailActivity::class.java)) }

        // 请注意确保在用户知情且同意的情况下，调用以下两个方法，规避合规问题
        TencentMapInitializer.setAgreePrivacy(true)
        TencentLocationManager.setUserAgreePrivacy(true)

        if (!(SPUtils.get(baseContext, "todaty_first_update_"+DateUtil.getToday(), false) as Boolean)) {
            CommonAppConfig.getObserverConfig().subscribe(object : DefaultObserver<ConfigBean?>() {
                override fun onError(e: Throwable) {
                    super.onError(e)
                    Toast.makeText(mContext, "无法连接服务器,请检查网络设置", Toast.LENGTH_SHORT).show()
                    Thread.sleep(1000)
                    exitProcess(0)
                }
                override fun onNext(configBean: ConfigBean) {
                    if (SdkVersionUtil.getAppVersion(mContext) < configBean.version.toInt()) {
                        val builder: DialogUitl.Builder = DialogUitl.Builder(mContext)
                        val build = builder.setTitle(WordUtil.getString(R.string.version_update))
                            .setContent("检测到有新版本可用，请立即更新")
                            .setConfrimString(WordUtil.getString(R.string.version_immediate_use))
                            .setCancelString(WordUtil.getString(R.string.version_not_update))
                            .setCancelable(configBean.forceUpdate == 1)
                            .setClickCallback(object : DialogUitl.SimpleCallback {
                                override fun onConfirmClick(dialog: Dialog?, content: String?) {
                                    if (!TextUtils.isEmpty(configBean.downloadApkUrl)) {
                                        openBrowser(baseContext, configBean.downloadApkUrl)
                                    } else {
                                        ToastUtil.showToast(R.string.version_download_url_error)
                                    }
                                }
                                override fun onCancelClick() {
                                    if (configBean.forceUpdate == 1) {
                                        exitProcess(0)
                                    } else {
                                        val today = DateUtil.getToday();
                                        SPUtils.put(baseContext, "todaty_first_update_$today", true);
                                    }
                                }
                            })
                            .build()
                        build.show()
                    }
                }
            })
        }
    }

    fun openBrowser(context: Context, url: String?) {
        val intent = Intent()
        intent.action = Intent.ACTION_VIEW
        intent.data = Uri.parse(url)
        context.startActivity(intent)
    }

    override fun initData() {
        initPermission()

    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
    }

    private fun initPermission() {
        mPermissionList.clear()//清空没有通过的权限
        for (i in permissionArray.indices) {
            if (!PermissionUtils.checkPhonePermission(this, permissionArray[i]))
                mPermissionList.add(permissionArray[i])
        }
        if (mPermissionList.size > 0) PermissionUtils.requestPermissions(
            this, permissionArray,
            REQ_CODE_INIT_API_KEY
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        var hasPermissionDismiss = false
        if (requestCode == REQ_CODE_INIT_API_KEY) {
            for (i in grantResults.indices) {
                if (grantResults[i] != PERMISSION_GRANTED) {
                    hasPermissionDismiss = true
                    ToastUtil.showToast(permissions.get(i) + " 没给");
                }
            }
            if (hasPermissionDismiss) showPermissionDialog()
        }
    }

    private fun showPermissionDialog() {
        if (!this::mPermissionDialog.isInitialized) {
            mPermissionDialog = AlertDialog.Builder(this)
                .setMessage("权限申请失败")
                .setPositiveButton("去设置") { _, _ ->
                    mPermissionDialog.dismiss()
                    //跳转到应用设置
                    val packageURI = Uri.parse("package:${BuildConfig.APPLICATION_ID}")
                    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI)
                    startActivity(intent)
                    this.finish()
                }
                .setNegativeButton("取消") { _, _ ->
                    mPermissionDialog.dismiss()
//                    this.finish()
                }
                .setCancelable(false)
                .create()
            mPermissionDialog.show()
        }
    }

    override fun initView() {
        titleResList = mutableListOf()
        titleResList.run {
            add(R.id.navigation_system)
            add(R.id.navigation_home)
            add(R.id.navigation_me)
        }
        //初始化ViewPager
        initViewPager()
        findViewById<BottomNavigationView>(R.id.bottom_bar).setOnNavigationItemSelectedListener {
            viewPager.currentItem = titleResList.indexOf(it.itemId);
            return@setOnNavigationItemSelectedListener true
        }
        //        LiveEventBus.get(MainEvent.UPDATE_USER_CENTER).observe(getActivity(), new Observer<Object>() {
//            @Override
//            public void onChanged(Object object){
//                requestData();
//            }
//        });
        zxingCodeUrl = findViewById<View>(R.id.zxingCodeUrl) as ImageView
        zxingCodeUrl?.setOnClickListener(View.OnClickListener { zxingCodeUrl!!.setVisibility(View.GONE) })
    }

    private fun initViewPager() {
        titleList = mutableListOf()
        titleList.run {
            add("拟卡")
            add("休闲")
            add("我的")
        }
        fragments = ArrayList()
        fragments.run {
            add(locationDetailFragment)
            add(videoLiveFragment)
            add(myFragment)
        }
        //初始化ViewPager,这是只能用viewPager，不能用viewPager2。2会滑动冲突，不好解决
        viewPager = findViewById<ViewPager>(R.id.vp2_fragment)
        val bottom_bar = findViewById<BottomNavigationView>(R.id.bottom_bar)
        val bottom_fab = findViewById<FloatingActionButton>(R.id.bottom_fab)
        viewPager.run {
            adapter = MainPagerAdapter()
            //解决滑动页面后再回来会刷新页面的问题，因为viewPager默认只预加载一页，多的页面会回收
            offscreenPageLimit = fragments.size
            addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {
                }

                @SuppressLint("WrongConstant")
                override fun onPageSelected(position: Int) {
                    pos = position
                    if (position == 1){
                        mToolbar?.visibility = View.GONE
                    }else {
                        mToolbar?.visibility = View.VISIBLE
                        setTopTitle(titleList[position])
                        setLeft("帮助文档") { WebViewActivity.start(it.context, "http://web.nowk.top//appapi/page/detail?id=4") }
                        setRight(null)
                    }
                    bottom_bar.selectedItemId = titleResList[position]
                    bottom_fab.setImageResource(if (1==position) R.mipmap.ic_home_select else R.mipmap.ic_home)
                    if (1!=position && videoLiveFragment!=null) {
                        videoLiveFragment.pauseVideo();
                    }
                }

                override fun onPageScrollStateChanged(state: Int) {}
            })
            viewPager.currentItem = pos
            bottom_fab.setImageResource(if (1==pos) R.mipmap.ic_home_select else R.mipmap.ic_home)
        }
    }

    inner class MainPagerAdapter : FragmentPagerAdapter(supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {

        override fun getCount(): Int = fragments.size

        override fun getItem(position: Int): Fragment {
            return fragments[position]
        }
    }

    override fun onResume() {
        // 动态注册网络变化广播
        val filter = IntentFilter()
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE")
        mNetworkChangeReceiver = NetworkChangeReceiver()
        registerReceiver(mNetworkChangeReceiver, filter)
        super.onResume()
    }

    override fun onPause() {
        if (mNetworkChangeReceiver != null) {
            unregisterReceiver(mNetworkChangeReceiver)
            mNetworkChangeReceiver = null
        }
        super.onPause()
    }

    var makeText: Toast? = null;
    @SuppressLint("ShowToast")
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        //判断用户是否点击的是返回键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //如果用户没有在2秒内再次按返回键的话，标记用户为不退出状态
            if (System.currentTimeMillis() - isExit <= 2000 || isFinishing) {
                makeText?.cancel()
                //退出程序
                onBackPressedDispatcher.onBackPressed()
            } else {
                isExit = System.currentTimeMillis()
                makeText = Toast.makeText(mContext, "再按一次退出应用", Toast.LENGTH_SHORT)
                makeText?.show();
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    fun toShowChargeUrl(qrCode: Bitmap) {
        zxingCodeUrl?.setImageBitmap(qrCode)
        zxingCodeUrl?.setVisibility(View.VISIBLE)
    }
}